package com.example.netty.netty.UDPExample;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Author: 江涛
 * @CreateTime: 2022-09-27  17:15
 * @Description:
 */
public class UDPServer {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(new NioEventLoopGroup())
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true) //设置SO_BROADCAST套接字选项,广播模式
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
                        ByteBuf byteBuf = msg.content();
                        byte[] bytes = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(bytes);
                        System.out.println("接收到消息："+new String(bytes));
                    }
                });

        Channel channel = bootstrap.bind(8000).sync().channel();
        //广播消息消息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            channel.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(s.getBytes()),
                    new InetSocketAddress("255.255.255.255", 7000)));
        }


    }
}
